import 'package:mobx/mobx.dart';
import 'package:thal/backstage/blueprint/group_chat_print.dart';

part 'group_chat_room.g.dart';

/// 群聊状态管理
class GroupChatRoom = _GroupChatRoom with _$GroupChatRoom;

abstract class _GroupChatRoom with Store {
  /// 群聊列表
  @observable
  ObservableList<GroupChatPrint> groupChats = ObservableList<GroupChatPrint>();

  /// 群聊消息列表
  @observable
  ObservableList<GroupChatMessagePrint> groupMessages =
      ObservableList<GroupChatMessagePrint>();

  /// 初始化默认群聊数据
  @action
  void initializeDefaultGroupChats() {
    groupChats = ObservableList<GroupChatPrint>.of([
      GroupChatPrint(
        id: '1',
        title: 'Lake Baikal',
        imageUrl: 'assets/images/team1.png',
        description:
            'Discussing the beauty and mysteries of Lake Baikal, the deepest lake in the world.',
        memberIds: [
          '1',
          '2',
          '3',
          '4',
        ], // admin, waterlover, lakephoto, naturefan
        createdAt: DateTime.now().subtract(const Duration(days: 10)),
      ),
      GroupChatPrint(
        id: '2',
        title: 'Crater Lake',
        imageUrl: 'assets/images/team2.png',
        description:
            'Sharing experiences and photos from Crater Lake National Park.',
        memberIds: [
          '1',
          '3',
          '5',
          '6',
        ], // admin, lakephoto, lakeexplorer, waterdream
        createdAt: DateTime.now().subtract(const Duration(days: 8)),
      ),
      GroupChatPrint(
        id: '3',
        title: 'Jade Lake',
        imageUrl: 'assets/images/team3.png',
        description:
            'Exploring the emerald waters and surrounding nature of Jade Lake.',
        memberIds: [
          '2',
          '4',
          '7',
          '8',
        ], // waterlover, naturefan, laketravel, waterpeace
        createdAt: DateTime.now().subtract(const Duration(days: 6)),
      ),
      GroupChatPrint(
        id: '4',
        title: 'Lake Como',
        imageUrl: 'assets/images/team4.png',
        description:
            'Italian lake adventures and villa tours around Lake Como.',
        memberIds: [
          '1',
          '2',
          '9',
          '10',
        ], // admin, waterlover, lakebeauty, waterwisdom
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
    ]);

    // 初始化默认消息数据
    groupMessages = ObservableList<GroupChatMessagePrint>.of([
      // Lake Baikal群聊消息
      GroupChatMessagePrint(
        id: '1',
        groupId: '1',
        userId: '1', // admin
        content:
            'Welcome everyone to the Lake Baikal group! Let\'s share our experiences.',
        createdAt: DateTime.now().subtract(const Duration(days: 9)),
      ),
      GroupChatMessagePrint(
        id: '2',
        groupId: '1',
        userId: '2', // waterlover
        content:
            'Lake Baikal is absolutely stunning! The water is so clear you can see 40 meters deep.',
        createdAt: DateTime.now().subtract(const Duration(days: 8)),
      ),
      GroupChatMessagePrint(
        id: '3',
        groupId: '1',
        userId: '3', // lakephoto
        content:
            'I captured some amazing photos of the ice formations last winter. Will share soon!',
        createdAt: DateTime.now().subtract(const Duration(days: 7)),
      ),
      GroupChatMessagePrint(
        id: '4',
        groupId: '1',
        userId: '4', // naturefan
        content:
            'The biodiversity around Baikal is incredible. So many unique species!',
        createdAt: DateTime.now().subtract(const Duration(days: 6)),
      ),

      // Crater Lake群聊消息
      GroupChatMessagePrint(
        id: '5',
        groupId: '2',
        userId: '1', // admin
        content:
            'Crater Lake is one of my favorite destinations. The blue color is mesmerizing!',
        createdAt: DateTime.now().subtract(const Duration(days: 7)),
      ),
      GroupChatMessagePrint(
        id: '6',
        groupId: '2',
        userId: '3', // lakephoto
        content:
            'The aerial view from the rim is absolutely breathtaking. Perfect for photography!',
        createdAt: DateTime.now().subtract(const Duration(days: 6)),
      ),
      GroupChatMessagePrint(
        id: '7',
        groupId: '2',
        userId: '5', // lakeexplorer
        content:
            'Has anyone done the boat tour to Wizard Island? Worth the trip?',
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      GroupChatMessagePrint(
        id: '8',
        groupId: '2',
        userId: '6', // waterdream
        content:
            'The peacefulness there is unmatched. Perfect for meditation and reflection.',
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),

      // Jade Lake群聊消息
      GroupChatMessagePrint(
        id: '9',
        groupId: '3',
        userId: '2', // waterlover
        content:
            'Jade Lake is like a hidden gem! The emerald color is so unique.',
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      GroupChatMessagePrint(
        id: '10',
        groupId: '3',
        userId: '4', // naturefan
        content:
            'The hiking trails around the lake offer amazing views. Highly recommended!',
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      GroupChatMessagePrint(
        id: '11',
        groupId: '3',
        userId: '7', // laketravel
        content: 'Best time to visit? Planning a trip there next month.',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      GroupChatMessagePrint(
        id: '12',
        groupId: '3',
        userId: '8', // waterpeace
        content:
            'The reflection of the mountains in the jade water is pure magic.',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),

      // Lake Como群聊消息
      GroupChatMessagePrint(
        id: '13',
        groupId: '4',
        userId: '1', // admin
        content:
            'Lake Como never fails to amaze me. The villas and gardens are spectacular!',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      GroupChatMessagePrint(
        id: '14',
        groupId: '4',
        userId: '2', // waterlover
        content:
            'Swimming in Lake Como is such a refreshing experience. The water is perfect!',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      GroupChatMessagePrint(
        id: '15',
        groupId: '4',
        userId: '9', // lakebeauty
        content:
            'The sunset views from the lakeside restaurants are absolutely romantic.',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      GroupChatMessagePrint(
        id: '16',
        groupId: '4',
        userId: '10', // waterwisdom
        content:
            'Lake Como teaches us about the harmony between nature and human architecture.',
        createdAt: DateTime.now().subtract(const Duration(hours: 12)),
      ),
    ]);
  }

  /// 获取所有群聊
  List<GroupChatPrint> fetchAllGroupChats() {
    return List.from(groupChats);
  }

  /// 根据ID获取群聊
  GroupChatPrint? fetchGroupChatById(String id) {
    try {
      return groupChats.firstWhere((group) => group.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户加入的群聊
  List<GroupChatPrint> fetchUserGroupChats(String userId) {
    return groupChats
        .where((group) => group.memberIds.contains(userId))
        .toList();
  }

  /// 获取群聊的所有消息
  List<GroupChatMessagePrint> fetchGroupMessages(String groupId) {
    return groupMessages.where((message) => message.groupId == groupId).toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); // 按时间排序
  }

  /// 获取群聊的最新消息
  GroupChatMessagePrint? fetchLatestGroupMessage(String groupId) {
    final messages = fetchGroupMessages(groupId);
    return messages.isNotEmpty ? messages.last : null;
  }

  /// 加入群聊
  @action
  bool joinGroupChat(String userId, String groupId) {
    try {
      final index = groupChats.indexWhere((group) => group.id == groupId);
      if (index != -1) {
        final group = groupChats[index];
        if (!group.memberIds.contains(userId)) {
          final updatedMemberIds = List<String>.from(group.memberIds)
            ..add(userId);
          final updatedGroup = GroupChatPrint(
            id: group.id,
            title: group.title,
            imageUrl: group.imageUrl,
            description: group.description,
            memberIds: updatedMemberIds,
            createdAt: group.createdAt,
          );
          groupChats[index] = updatedGroup;
          return true;
        }
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 退出群聊
  @action
  bool leaveGroupChat(String userId, String groupId) {
    try {
      final index = groupChats.indexWhere((group) => group.id == groupId);
      if (index != -1) {
        final group = groupChats[index];
        if (group.memberIds.contains(userId)) {
          final updatedMemberIds = List<String>.from(group.memberIds)
            ..remove(userId);
          final updatedGroup = GroupChatPrint(
            id: group.id,
            title: group.title,
            imageUrl: group.imageUrl,
            description: group.description,
            memberIds: updatedMemberIds,
            createdAt: group.createdAt,
          );
          groupChats[index] = updatedGroup;
          return true;
        }
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 发送消息到群聊
  @action
  bool sendGroupMessage(String groupId, String userId, String content) {
    try {
      final newMessage = GroupChatMessagePrint(
        id: '${DateTime.now().millisecondsSinceEpoch}',
        groupId: groupId,
        userId: userId,
        content: content,
        createdAt: DateTime.now(),
      );
      groupMessages.add(newMessage);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 检查用户是否是群聊成员
  bool isGroupMember(String userId, String groupId) {
    final group = fetchGroupChatById(groupId);
    return group?.memberIds.contains(userId) ?? false;
  }

  /// 获取群聊成员数量
  int getGroupMemberCount(String groupId) {
    final group = fetchGroupChatById(groupId);
    return group?.memberIds.length ?? 0;
  }

  /// 获取群聊消息数量
  int getGroupMessageCount(String groupId) {
    return groupMessages.where((message) => message.groupId == groupId).length;
  }

  /// 创建新群聊
  @action
  bool createGroupChat({
    required String title,
    required String imageUrl,
    required String description,
    required String creatorId,
  }) {
    try {
      final newGroup = GroupChatPrint(
        id: (groupChats.length + 1).toString(),
        title: title,
        imageUrl: imageUrl,
        description: description,
        memberIds: [creatorId], // 创建者自动加入
        createdAt: DateTime.now(),
      );
      groupChats.add(newGroup);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除群聊
  @action
  bool deleteGroupChat(String groupId) {
    try {
      groupChats.removeWhere((group) => group.id == groupId);
      groupMessages.removeWhere((message) => message.groupId == groupId);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取群聊总数
  int get groupChatCount => groupChats.length;

  /// 获取用户加入的群聊数量
  int getUserGroupChatCount(String userId) {
    return groupChats.where((group) => group.memberIds.contains(userId)).length;
  }
}
